from soj.builtin.scoring.subtask import get_policy_by_dict,TestcaseConfig,SubtaskConfig

def _resolve_config(config:dict)->SubtaskConfig:
    if "type" not in config:
        raise ValueError("Subtask config missing 'type' field")
    if "id" not in config:
        raise ValueError("Subtask config missing 'id' field")
    if config["type"]=="subtask":
        current_node:SubtaskConfig={
            "real_id":config["id"],
            "sub":[],
        }
        if "policy" not in config:
            raise ValueError("Subtask config missing 'policy' field")
        current_node["policy"]=get_policy_by_dict(config["policy"])
        if "sub" not in config:
            raise ValueError("Subtask config missing 'sub' field")
        for i in config["sub"]:
            current_node["sub"].append(_resolve_config(i))
        return current_node
    elif config["type"]=="testcase":
        if "id" not in config:
            raise ValueError("Testcase config missing 'id' field")
        return {
            "real_id":config["id"],
        }
    else:
        raise ValueError(f"Unknown config type: {config['type']}")

def resolve_scoring_config(config:dict)->SubtaskConfig:
    if "type" not in config or config["type"]!="subtask":
        raise ValueError("Root scoring config must be a subtask")
    config["id"]=-1 # Root config id must be -1
    if "policy" not in config:
        raise ValueError("Root scoring config missing 'policy' field")
    return _resolve_config(config)